import socket


class WebServer(object):
    def __init__(self):
        tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)        
        tcp_socket.bind(('', 8080))
        tcp_socket.listen(128)
        self.tcp_socket = tcp_socket
    def start(self):
         while True:
            new_socket, ip_port = self.tcp_socket.accept()
            print('%s上线啦' %str(ip_port))
            self.request_heandler(new_socket, ip_port)

    def request_heandler(self, new_socket, ip_port):
        recv_data = new_socket.recv(1024).decode()
        if not recv_data:
            print("%s已下线" % str(ip_port))
            new_socket.close()
            return
        loc = recv_data.find('\r\n')
        request_line = recv_data[:loc]
        request_line_list = request_line.split(' ')
        request_path = request_line_list[1]
        if (request_path == '/'):
            request_path = 'index.html'
        
        response_line = "HTTP/1.1 200 OK\r\n"
        response_header = "Server:JianKun\r\n"
        response_blank = "\r\n"
        response_body = ""

        try:
            with open("/Users/yangjiankun/Documents/python_review/web_serve_easy/static"+request_path, 'rb') as file:
                response_body = file.read()
        except Exception as e:
            response_line = "HTTP/1.1 404 NOTFOND\r\n"
            response_body = ("%s" %e).encode()

        response = (response_line + response_header + response_blank).encode() + response_body
        new_socket.send(response) 
        new_socket.close()

def main():
    ws = WebServer()
    ws.start()

if __name__ == '__main__':
    main()
    